package cn.tedu.v1.service.impl;

import cn.tedu.v1.exception.ServiceException;
import cn.tedu.v1.mapper.*;
import cn.tedu.v1.model.*;
import cn.tedu.v1.service.IDoctorsService;
import cn.tedu.v1.vo.DoctorVo;
import cn.tedu.v1.vo.UpdateDocVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.management.Query;
import javax.print.Doc;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 医生列表 服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-07-06
 */
@Service
@Slf4j
public class DoctorsServiceImpl extends ServiceImpl<DoctorsMapper, Doctors> implements IDoctorsService {
    @Resource
    DoctorsMapper doctorsMapper;
    @Resource
    private DepartmentOfficeMapper departmentOfficeMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;
    QueryWrapper query = new QueryWrapper();
    private final PasswordEncoder encoder = new BCryptPasswordEncoder();

    @Value("${imagePath}")
    private String imagePath;

    //根据科室id查询出对应的医生
    @Override
    public List<Doctors> getDoctorsByOfficeId(Integer officeId) {
        List<Doctors> doctors = doctorsMapper.selectDoctorsByOfficeId(officeId);

        return doctors;
    }

    //定义一个医生角色的常量
    private final String doctorRole = "ROLE_DOCTOR";



    /*
       添加医生,同时注册一个新医生的账户,并设置角色
     */


    @Override
    @Transactional
    public String addDoctor(@Validated DoctorVo doctorVo) {
        //得到头像文件
        MultipartFile file = doctorVo.getPicture();
        //获取文件名
        String picName = file.getOriginalFilename();
        //得到文件后缀名
        String suffix = picName.substring(picName.lastIndexOf("."));
        //得到唯一的文件名
        picName = UUID.randomUUID() + suffix;
        //创建一个以部门命名的的路径
        log.debug("docvorVo里的departmentId:{}",doctorVo.getDepartmentId());
        query.clear();
        query.eq("office_id", doctorVo.getDepartmentId());
        DepartmentOffice d = departmentOfficeMapper.selectOne(query);
        log.debug("对应的部门对象:{}", d);
        log.debug("部门id:{}", d.getDepartmentId());
        log.debug("科室id:{}", d.getOfficeId());
        String dpName = d.getDepartmentId() + "/" + d.getOfficeId();
        String path = imagePath + "/" + dpName;

        //生成图片的保存路径
        String picPath = path + "/" + picName;

        //创建一个医生对象,将接收到的医生注册信息保存在对象里
        Doctors doctor = new Doctors();
        doctor.setName(doctorVo.getName())
                .setGender(doctorVo.getGender())
                .setEmail(doctorVo.getEmail())
                .setPhone(doctorVo.getPhone())
                .setOfficeId(doctorVo.getDepartmentId())
                .setHeadimgUrl("/" + dpName + "/" + picName)
                .setBloodtype(doctorVo.getBloodType())
                .setBirthday(doctorVo.getBirthday())
                .setOtherinfo(doctorVo.getIntroduce())
                .setStatus(1);
        log.debug("新添加的医生信息:" + doctor);


        //先将用户信息填好
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String pw = "{bcrypt}" + encoder.encode(doctorVo.getPassword());
        User user = new User();
        user.setUsername(doctorVo.getUsername())
                .setPassword(pw)
                .setName(doctorVo.getName())
                .setGender(doctorVo.getGender())
                .setEmail(doctorVo.getEmail())
                .setPhone(doctorVo.getPhone())
                .setBloodType(doctorVo.getBloodType());
        //设置两个用于接收mapper返回值的对象
        int num1;
        int num2;
        //再检测用户是否注册过
        query.clear();
        query.eq("username", doctorVo.getUsername());
        User user1 = userMapper.selectOne(query);
        //如果用户名已经存在
        if (user1 != null) {
            query.clear();
            query.eq("name", user1.getName());
            doctor = doctorsMapper.selectOne(query);
            //并且已经是医生
            if (doctor != null) {
                return "该用户名已存在并已经是医生";
            }
            //如果还不是医生,利用当前填写的医生信息更新一下用户表里的相关数据
            user.setId(user1.getId());
            num1 = userMapper.updateById(user);
            //如果用户名不存在,则创建用户
        } else {
            num1 = userMapper.insert(user);
        }

        num2 = doctorsMapper.insert(doctor);
        //添加用户完成后还要设置用户角色,也就是完善user_role表
        //再获取刚才新添加或更新的用户对象
        query.clear();
        query.eq("name", user.getName());
        user = userMapper.selectOne(query);
        //获取一个role对象,查询医生角色的id
        query.clear();
        query.eq("name", doctorRole);
        Role role = new Role();
        role = roleMapper.selectOne(query);
        //将获取的两个参数放入创建的user_role对象
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId())
                .setRoleId(role.getId());
        //将其插入表格中
        userRoleMapper.insert(userRole);
        if (num1 == 1 && num2 == 1) {
            //数据库操作成功后,再创建表示文件夹的文件对象
            File picfile = new File(picPath);
            //若文件夹不存在则创建
            if (!picfile.exists()) {
                picfile.mkdirs();
            }
            try {
                //把文件保存到上面的文件夹中
                file.transferTo(new File(picPath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "1";
        } else {
            throw new ServiceException("服务器忙");
        }

    }

    @Override
    public List<Doctors> getAllDoctors() {
        //清空之前的query语句条件
        query.clear();
        query.eq("status","1");
        //按照officeID排序
        query.orderByAsc("office_id");
        List<Doctors> list = doctorsMapper.selectList(query);
        for (Doctors d : list) {
            //根据id得到部门名字存入相应的医生对象里,
            Integer dpId = d.getOfficeId();
            log.debug("得到的officeid:{}", dpId);
            DepartmentOffice departmentOffice = departmentOfficeMapper.selectById(dpId);
            log.debug("得到的departmentoffice:{}", departmentOffice);
            String dpname = departmentOffice.getOfficeName();
            log.debug("得到的dpname:{}", dpname);
            d.setDepartmentName(dpname);
        }
        return list;
    }

    //编辑修改医生
    @Override
    public String updateDoctor(UpdateDocVo doctorVo) {


        //创建一个医生对象
            Doctors doctor=new Doctors();

            //先存入不需要判断的信息
            doctor.setId(doctorVo.getId())
                    .setName(doctorVo.getName())
                    .setPhone(doctorVo.getPhone())
                    .setOfficeId(doctorVo.getDepartmentId())
                    .setBloodtype(doctorVo.getBloodType())
                    .setBirthday(doctorVo.getBirthday())
                    .setOtherinfo(doctorVo.getIntroduce())
                    .setGender(doctorVo.getGender())
                    .setEmail(doctorVo.getEmail());

            //是否更改了头像需要判断
        //得到头像文件
        MultipartFile file = doctorVo.getPicture();
        String picPath="";//创建一个图片保存路径
        if(doctorVo.getPicture()!=null){
            //获取文件名
            String picName = file.getOriginalFilename();
            //得到文件后缀名
            String suffix = picName.substring(picName.lastIndexOf("."));
            //得到唯一的文件名
            picName = UUID.randomUUID() + suffix;
            //创建一个以部门命名的的路径

            query.eq("office_id", doctorVo.getDepartmentId());
            DepartmentOffice d = departmentOfficeMapper.selectOne(query);
            log.debug("对应的部门对象:{}", d);
            log.debug("部门id:{}", d.getDepartmentId());
            log.debug("科室id:{}", d.getOfficeId());
            String dpName = d.getDepartmentId() + "/" + d.getOfficeId();
            String path = imagePath + "/" + dpName;
            //生成图片的保存路径
            picPath = path + "/" + picName;
            doctor.setHeadimgUrl("/" + dpName + "/" + picName);
            //用update方法更新医生信息
            int num1=  doctorsMapper.updateById(doctor);
            if (num1 == 1 ) {
                //数据库操作成功后,再创建表示文件夹的文件对象
                File picfile = new File(picPath);
                //若文件夹不存在则创建
                if (!picfile.exists()) {
                    picfile.mkdirs();
                }
                try {
                    //把文件保存到上面的文件夹中
                    file.transferTo(new File(picPath));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "更新成功";
            } else {
                throw new ServiceException("服务器忙");
            }


        }else{
            int num1=  doctorsMapper.updateById(doctor);
            if (num1 == 1) {
                return "更新成功!";
            }else{
                throw new ServiceException("服务器忙");
            }
        }
    }

    //根据id删除医生
    @Override
    public String deleteDoctor(Integer id) {
        //删除医生只是改变status表字段的值,不删数据
        Doctors doctor=doctorsMapper.selectById(id);
       doctor.setStatus(0);
        int num=doctorsMapper.updateById(doctor);
        if(num==1){
            return "删除成功!";
        }else{
            throw new ServiceException("服务器忙!");
        }
    }
}

